package com.yang.flower.controller;

import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.captcha.CaptchaUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yang.flower.common.Constants;
import com.yang.flower.common.Result;
import com.yang.flower.config.AuthAccess;
import com.yang.flower.dto.UserDTO;
import com.yang.flower.entity.User;
import com.yang.flower.service.UserService;
import com.yang.flower.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description: 用户管理
 * @Author: Yang
 * @DateTime: 2022/11/11 9:19
 **/
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //分页查询
    @GetMapping("/page")
    public Page<User> findPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam String username,
                               @RequestParam String email,
                               @RequestParam String address){
        Page<User> page = new Page<User>(pageNum,pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(User::getUsername,username);
        queryWrapper.like(User::getEmail,email);
        queryWrapper.like(User::getAddress,address);
        queryWrapper.orderByDesc(User::getCreateTime);

        User currentUser = TokenUtils.getCurrentUser();
        System.out.println("西瓜"+currentUser.getName());

        Page<User> userPage = userService.page(page,queryWrapper);
        return userPage;
    }

    //新增用户
    @PostMapping("/save")
    public Boolean add(@RequestBody User user){
        user.setPassword("123456");
        user.setCreateTime(DateTime.now());
        return userService.save(user);
    }

   //编辑用户
   @PutMapping("/edit")
    public Boolean edit(@RequestBody User user){
        return userService.updateById(user);
   }

   //根据id删除用户
   @DeleteMapping("/delete/{id}")
    public Boolean delete(@PathVariable("id") String id){
        return userService.removeById(id);
   }

   //批量删除用户
   @DeleteMapping("/deleteBatch")
    public Boolean deleteBatch(@RequestBody List<Integer> ids){
        return userService.removeByIds(ids);
   }

   //根据id查询用户
   @GetMapping("/{id}")
   public Result queryById(@PathVariable Integer id){
        return Result.success(userService.getById(id));
   }

    //导出
    @GetMapping("/export")
    @AuthAccess
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<User> list = userService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("avatarUrl", "头像");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO){
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
        UserDTO dto = userService.login(userDTO);
        return Result.success(dto);
    }

    //注册
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        System.out.println("user:"+user);
        String username = user.getUsername();
        String password = user.getPassword();
        if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }

        return Result.success(userService.register(user));
    }

    @AuthAccess
    @GetMapping("/getCode")
    public void getCode(HttpServletRequest request,HttpServletResponse response){
        response.setHeader("pragma","no-cache");
        response.setHeader("cache-control","no-cache");
        response.setHeader("expires","0");
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(123, 40, 4, 5);
        String code = captcha.getCode();
        System.out.println("code: " + code);
        HttpSession session = request.getSession();
        captcha.write("d:/circle.png");
        session.setAttribute("code",code);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            captcha.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
